local bugun = fk.CreateSkill{
  name = "investiture__bugun",
  tasg = { "Turn" },
}

Fk:loadTranslationTable{
  ["investiture__bugun"] = "补衮",
  [":investiture__bugun"] = "回合技，当你判定时，可以弃置牌堆顶与一名角色各一张牌，你选择其中一张作为判定牌。若之为黑桃/你的牌，则你横置至多三名角色/观看并分配牌堆顶两张牌。",

  ["#investiture__bugun-invoke"] = "补衮：可以弃置牌堆顶与一名角色各一张牌，选择其中一张作为判定牌",
  ["#investiture__bugun-choose"] = "补衮：请选择一张牌作为判定牌",
  ["#investiture__bugun-chain"] = "补衮：横置至多三名角色",
}

local U = require "packages/utility/utility"

bugun:addEffect(fk.StartJudge, {
  anim_type = "special",
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(bugun.name) and target == player and player:usedSkillTimes(bugun.name) == 0
    and table.find(player.room.alive_players, function (p)
      return not p:isKongcheng()
    end)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local to = room:askToChoosePlayers(player, {
      targets = table.filter(room.alive_players, function(p) return not p:isKongcheng() end),
      max_num = 1,
      min_num = 1,
      skill_name = bugun.name,
      cancelable = true,
      prompt = "#investiture__bugun-invoke",
    })
    if #to == 1 then
      event:setCostData(self, to[1])
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local to = event:getCostData(self) ---@type ServerPlayer
    local room = player.room
    local cardA = room:askToChooseCard(player, {
      target = to,
      flag = "he",
      skill_name = bugun.name,
    })
    local cardB = room:getNCards(1)[1]

    room:moveCards({
      ids = {cardA},
      toArea = Card.DiscardPile,
      proposer = player,
      skillName = bugun.name,
      moveReason = fk.ReasonDiscard,
      moveVisible = true,
      from = to,
    }, {
      ids = {cardB},
      toArea = Card.DiscardPile,
      proposer = player,
      skillName = bugun.name,
      moveReason = fk.ReasonDiscard,
      moveVisible = true,
    })

    local card, _ = room:askToChooseCardsAndChoice(player, {
      cards = {cardA, cardB},
      choices = {"OK"},
      skill_name = bugun.name,
      prompt = "#investiture__bugun-choose",
      max_num = 1,
      min_num = 1,
    })
    data.card = Fk:getCardById(card[1])

    if data.card:getSuitString() == "spade" then
      local tos = room:askToChoosePlayers(player, {
        targets = table.filter(room:getAlivePlayers(), function (p) return not p.chained end),
        min_num = 0,
        max_num = 3,
        skill_name = bugun.name,
        prompt = "#investiture__bugun-chain",
      })
      table.forEach(tos, function (p)
        p:setChainState(true)
      end)
    end
    if card[1] == cardA and player == to then
      local cards = room:getNCards(2)
      room:askToYiji(player, {
        cards = cards,
        expand_pile = cards,
        max_num = 2,
        min_num = 2,
        skill_name = bugun.name,
      })
    end
  end
})

return bugun